package com.xique.blelock.view;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.baidu.autoupdatesdk.BDAutoUpdateSDK;
import com.baidu.autoupdatesdk.UICheckUpdateCallback;
import com.clj.fastble.BleManager;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.utils.HexUtil;
import com.ivin.crop.Log;
import com.ivin.refreshlayout.QRefreshLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.xique.blelock.Adapter.FingerAdapter;
import com.xique.blelock.Adapter.LockinfoAdapter;
import com.xique.blelock.Interface.BleConnectListen;
import com.xique.blelock.Interface.OnItemClickListener;
import com.xique.blelock.Jpush.JpushUtil;
import com.xique.blelock.NetUtils.NetResult;
import com.xique.blelock.NetUtils.XqNetClient;
import com.xique.blelock.R;
import com.xique.blelock.Utils.ACache;
import com.xique.blelock.Utils.BSSIDUtil;
import com.xique.blelock.Utils.BleUtils;
import com.xique.blelock.Utils.Stringkey;
import com.xique.blelock.Utils.TimeUtil;
import com.xique.blelock.model.FingerInfo;
import com.xique.blelock.model.HistoryMessageInfo;
import com.xique.blelock.model.LockAllinfo;
import com.xique.blelock.model.LockInfo;
import com.xique.blelock.model.UserInfo;
import com.xique.blelock.model.UserOfLockinfo;
import com.xique.blelock.view.AcountManager.FingerListActivty;
import com.xique.blelock.view.AcountManager.Myself_Activity;
import com.xique.blelock.view.AcountManager.UserListActivity;
import com.xique.blelock.view.DeviceManager.Adddevice_Activity;
import com.xique.blelock.view.DeviceManager.ConnectAnimationActivity;
import com.xique.blelock.view.DeviceManager.DeviceControllerActivity;
import com.xique.blelock.view.Setting.Message_Activity;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
import com.yanzhenjie.recyclerview.swipe.widget.DefaultItemDecoration;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jiguang.net.HttpResponse;
import cn.jiguang.net.HttpUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class Home_Activity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = Home_Activity.class.getSimpleName();
    private Button ADDdevice;
    private ImageView Myselfcent,Messagecent;

    @BindView(R.id.mydevicelist)
    SwipeMenuRecyclerView recyclerView;

    @BindView(R.id.devicelayout)
    View devicelayout;

//    @BindView(R.id.refreshLayout)
//    QRefreshLayout refreshLayout;

    @BindView(R.id.messagetip)
    TextView messagetip;


    @BindView(R.id.nodevicelayout)
    View nonedevicelayout;



    private List<LockInfo> lockInfoList = new ArrayList<>();

    private LockinfoAdapter lockinfoAdapter;

    private UserInfo userInfo;
    private final static int Search_device_request = 1001;
    private BroadcastReceiver mReceiver;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.zhuyeactivity);
        ButterKnife.bind(this);
        iniotview();
        initBle();
        //判断是否已经设置过极光推送别名
        Boolean issetting = (Boolean) ACache.get(this).getAsObject(Stringkey.JpushTag);
        if(issetting == null  || (!issetting))
        {
            JpushUtil.setAlias();
        }

        TestBle();

        IntentFilter filter = new IntentFilter();
        filter.addAction(Stringkey.Message_Event);
        filter.addAction(Stringkey.Device_ReGetDeviceList);
        mReceiver = new MessagePush();
        this.registerReceiver(mReceiver, filter);
        BDAutoUpdateSDK.uiUpdateAction(this, new MyUICheckUpdateCallback());
    }

    // 捕获返回键的方法2
    @Override
    public void onBackPressed() {
        Log.e("onBackPressed()", TAG);
        super.onBackPressed();



    }

    private class MyUICheckUpdateCallback implements UICheckUpdateCallback {

        @Override
        public void onNoUpdateFound() {
            Log.e("没有发现新的安装包---", "");
        }

        @Override
        public void onCheckComplete() {
           Log.e("百度更新安装包完成---", "");
        }

    }


    private Boolean hasMessage = false;
    @Override
    protected void onResume() {
        super.onResume();
        //这里获取设备列表
        getMydeviceList();

        //ACache.get(MyApplication.context).put(Stringkey.HasMessage, true);
        Boolean temp  = (Boolean) ACache.get(this).getAsObject(Stringkey.HasMessage);
        if(temp == null){
            hasMessage = false;
        }else{
            hasMessage = temp;
        }
        if(hasMessage){
            messagetip.setVisibility(View.VISIBLE);
        }else{
            messagetip.setVisibility(View.GONE);
        }

    }

    private void iniotview() {
        ADDdevice = findViewById(R.id.aadddevice);
        Myselfcent = findViewById(R.id.MYSELF);
//        Messagecent = findViewById(R.id.messagecent);
//        Messagecent.setOnClickListener(this);
        Myselfcent.setOnClickListener(this);
        ADDdevice.setOnClickListener(this);

        userInfo = (UserInfo) ACache.get(this).getAsObject(Stringkey.USERInfo);


        recyclerView.setLayoutManager(new LinearLayoutManager(this));
//        recyclerView.addItemDecoration(new DefaultItemDecoration(ContextCompat.getColor(this, R.color.divider_primary)));
//        recyclerView.setSwipeItemClickListener(mItemClickListener);
        recyclerView.setSwipeMenuCreator(swipeMenuCreator);
        recyclerView.setSwipeMenuItemClickListener(mMenuItemClickListener);

        lockinfoAdapter = new LockinfoAdapter(lockInfoList);
        recyclerView.setAdapter(lockinfoAdapter);

        lockinfoAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(Object object, int position) {
                final LockInfo lockInfo = (LockInfo) object;
                Log.e("准备连接设备"+ com.alibaba.fastjson.JSONObject.toJSONString(lockInfo), "");

                if(lockInfo.getLockId().length() != 12){
                    showToast(Home_Activity.this,"蓝牙地址非法");
                    return;
                }

                int timeout = 1;
                if(BleManager.getInstance().isConnected(BleUtils.getBleDevice())){
                    if(!BleUtils.getBleDevice().getMac().replace(":","").equalsIgnoreCase(lockInfo.getLockId()))
                    {
                        BleManager.getInstance().disconnect(BleUtils.getBleDevice());
                        timeout = 200;
                    }

                }

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent;
                        if(BleManager.getInstance().isConnected(BleUtils.getBleDevice())){

                            intent = new Intent(Home_Activity.this, DeviceControllerActivity.class);
                            intent.putExtra(Stringkey.DeviceInfo, BleUtils.getBleDevice());
                        }else{
                            intent = new Intent(Home_Activity.this, ConnectAnimationActivity.class);
                        }

                        intent.putExtra(Stringkey.BLEDevice, lockInfo);
                        startActivity(intent);
                    }
                }, timeout);



            }
        });



    }



    /**
     * 菜单创建器，在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int position) {
            int width = getResources().getDimensionPixelSize(R.dimen.dp_70);
            int widthlarge = getResources().getDimensionPixelSize(R.dimen.dp_100);
            LockInfo lockInfo = lockInfoList.get(position);
            // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
            // 2. 指定具体的高，比如80;
            // 3. WRAP_CONTENT，自身高度，不推荐;
            int height = ViewGroup.LayoutParams.MATCH_PARENT;



            // 添加右侧的，如果不添加，则右侧不会出现菜单。
            {
                //如果当前设备被手机连接，提示一个断开按钮
                if((lockInfo.getLockId().length() == 12) && BleManager.getInstance().isConnected(BSSIDUtil.restoreBSSID(lockInfo.getLockId()).toUpperCase())) {
                    SwipeMenuItem addItem = new SwipeMenuItem(Home_Activity.this).setBackground(R.color.green_pressed)
                            .setText("断开设备")
                            .setTextColor(Color.WHITE)
                            .setWidth(width)
                            .setHeight(height);
                    swipeRightMenu.addMenuItem(addItem); // 添加菜单到右侧。
                    lockInfo.setMenunum(3);
                }else{
                    lockInfo.setMenunum(2);
                }

                //再继续判断自己是不是管理员


                SwipeMenuItem addItem = new SwipeMenuItem(Home_Activity.this).setBackground(R.color.coloblueAY)
                        .setText("编辑")
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height);
                swipeRightMenu.addMenuItem(addItem); // 添加菜单到右侧。


                SwipeMenuItem deleteItem = new SwipeMenuItem(Home_Activity.this).setBackground(R.drawable.selector_red)
//                        .setImage(R.mipmap.ic_action_delete)
                        .setText("删除")
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height);

                swipeRightMenu.addMenuItem(deleteItem);// 添加菜单到右侧。

            }
        }
    };



    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private SwipeMenuItemClickListener mMenuItemClickListener = new SwipeMenuItemClickListener() {
        @Override
        public void onItemClick(SwipeMenuBridge menuBridge, int position) {
            menuBridge.closeMenu();
            LockInfo lockInfo = lockInfoList.get(position);
            int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
            int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。


            if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
                //Toast.makeText(FingerListActivty.this, "list第" + position + "; 右侧菜单第" + menuPosition, Toast.LENGTH_SHORT)
                //.show();
                if(lockInfo.getMenunum() == 2) {
                    if (menuPosition == 1) {
                        showdeletDialog(position);
                    }
                    if (menuPosition == 0) {//编辑指纹信息的名称
                        showEditname(position);
                    }
                }else{
                    if (menuPosition == 2) {
                        showdeletDialog(position);
                    }
                    if (menuPosition == 1) {//编辑指纹信息的名称
                        showEditname(position);
                    }
                    if (menuPosition == 0) {//编辑指纹信息的名称
                        BleManager.getInstance().disconnect(BleUtils.getBleDevice());
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                lockinfoAdapter.notifyDataSetChanged();
                            }
                        }, 200);

                    }
                }
            } else if (direction == SwipeMenuRecyclerView.LEFT_DIRECTION) {
                Toast.makeText(Home_Activity.this, "list第" + position + "; 左侧菜单第" + menuPosition, Toast.LENGTH_SHORT)
                        .show();
            }
        }
    };

    //提示是否需要删除  解除锁和用户的绑定关系
    protected void showdeletDialog(final int position) {

        new MaterialDialog.Builder(this)// 初始化建造者
                .title("提示")// 标题
                .content("确定要删除吗？")// 内容
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        deleLockinfo(lockInfoList.get(position));
                    }
                })
                .show();// 显示对话框

    }


    private void showEditname(final int position) {
    new MaterialDialog.Builder(this)
                .title("修改名字")// 标题
                .inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PERSON_NAME)// 输入类型
                .input("请输入需要改的名字", "", new MaterialDialog.InputCallback() {
                    @Override
                    public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                        //Toast.makeText(FingerListActivty.this, "do something...", Toast.LENGTH_SHORT).show();

                    }
                })
                .negativeText("取消")
                .negativeColor(getResources().getColor(R.color.grey))
                .positiveText("确定")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if(TextUtils.isEmpty(dialog.getInputEditText().getText())){
                            showToast(Home_Activity.this,"请输入名字");
                            return;
                        }
                        updateLockaName(position, dialog.getInputEditText().getText().toString());
                    }
                })
                .show();// 显示对话框
    }

    private void deleLockinfo(LockInfo lockInfo) {
        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();

        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("lockId",lockInfo.getLockId());//E0:4C:63:6D:82:43
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        showProgressDialog();
        netClient.deleteLock(jsonobject.toString()).enqueue(new Callback<NetResult>() {//获取验证码
            @Override
            public void onResponse(Call<NetResult> call, Response<NetResult> response) {
                hideProgressDialog();
                Log.e("删除用户信息=== "+response, "");
                if(response.body().isSuccess()){
                    showToast(Home_Activity.this, "删除设备成功");
                    getMydeviceList();
                    //设备上也需要删除指纹
                }else {
                    showToast(Home_Activity.this, "删除设备失败:"+response.body().getMessage());
                }

            }

            @Override
            public void onFailure(Call<NetResult> call, Throwable t) {
                t.printStackTrace();
                hideProgressDialog();

            }
        });
    }
    private void updateLockaName(int position, String nickname) {
        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();

        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("lockId", lockInfoList.get(position).getLockId());//E0:4C:63:6D:82:43
            jsonobject.put("lockName", nickname);
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        showProgressDialog();
        netClient.updateLockaName(jsonobject.toString()).enqueue(new Callback<NetResult>() {//获取验证码
            @Override
            public void onResponse(Call<NetResult> call, Response<NetResult> response) {
                hideProgressDialog();
                Log.e("删除用户信息=== "+response, "");
                if(response.body().isSuccess()){
                    showToast(Home_Activity.this, "更新名称成功");
                    getMydeviceList();
                    //设备上也需要删除指纹
                }else {
                    showToast(Home_Activity.this, "更新名称失败");
                }

            }

            @Override
            public void onFailure(Call<NetResult> call, Throwable t) {
                t.printStackTrace();
                hideProgressDialog();

            }
        });
    }

    //删除绑定设备的普通用户
    private void deletUserFromDevice(LockInfo lockInfo) {
        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();

        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("lockId", lockInfo.getLockId());//E0:4C:63:6D:82:43
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        showProgressDialog();
        netClient.deleteLock(jsonobject.toString()).enqueue(new Callback<NetResult>() {//获取验证码
            @Override
            public void onResponse(Call<NetResult> call, Response<NetResult> response) {

                Log.e("删除锁结果== "+response, "");
                if(response.body().isSuccess()){
                    showToast(Home_Activity.this, "删除锁成功");
                    getMydeviceList();
                }else {
                    showToast(Home_Activity.this, "删除锁失败");
                }
                hideProgressDialog();
            }

            @Override
            public void onFailure(Call<NetResult> call, Throwable t) {
                t.printStackTrace();
                hideProgressDialog();

            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v == ADDdevice) {

            jumpAddDevicePage();
        } else if (v == Myselfcent) {
            Intent serverIntent = new Intent(this, Myself_Activity.class); // 跳转个人中心

            startActivity(serverIntent);
        }
    }

    @OnClick(R.id.messagelayout)
    public void MessageCenter(){
        Intent serverIntent = new Intent(this, Message_Activity.class); // 跳转信息
        startActivity(serverIntent);
    }

    @OnClick(R.id.addevicebtn)
    public void addDevice(){
        jumpAddDevicePage();
    }

    private void jumpAddDevicePage(){
        Intent serverIntent = new Intent(this, Adddevice_Activity.class); // 跳设备添加界面
        startActivityForResult(serverIntent, Search_device_request);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == Search_device_request && (resultCode == RESULT_OK)){
            getMydeviceList();
        }
    }

    //查询大年设备和用户之间的关系
    private void getMydeviceList(){

        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();

        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");

        } catch (JSONException e) {
            e.printStackTrace();
        }

        showProgressDialog();
        netClient.queryLockList(jsonobject.toString()).enqueue(new Callback<NetResult<List<LockInfo>>>(){//获取验证码
            @Override
            public void onResponse(Call<NetResult<List<LockInfo>>> call, Response<NetResult<List<LockInfo>>> response) {
                if(response.body().isSuccess()){
                    lockInfoList = response.body().getData();
                    userInfo.setLockInfoList(lockInfoList);
                    ACache.get(Home_Activity.this).put(Stringkey.USERInfo, userInfo);
                    Log.e("获取到的锁列表 ："+ JSON.toJSONString(lockInfoList), "");
                    if(lockInfoList.size() >0){
                        nonedevicelayout.setVisibility(View.GONE);
                        devicelayout.setVisibility(View.VISIBLE);
                        lockinfoAdapter.setDeviceList(lockInfoList);
                        lockinfoAdapter.notifyDataSetChanged();
                    }else{
                        nonedevicelayout.setVisibility(View.VISIBLE);
                        devicelayout.setVisibility(View.GONE);
                    }
                }else {
                    showToast(Home_Activity.this, "没有获取到设备列表 ");
                }
                hideProgressDialog();
            }

            @Override
            public void onFailure(Call<NetResult<List<LockInfo>>> call, Throwable t) {
                t.printStackTrace();
                hideProgressDialog();

            }
        });
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        BleUtils.stopNotify();
        BleManager.getInstance().disconnectAllDevice();
        BleManager.getInstance().destroy();
        super.onDestroy();

    }

    //http://47.107.227.104:8080/Advert/advert/BleTest
    private void TestBle(){


        new Thread()
        {
            public void run()
            {
                try
                {
                    HttpResponse ret = HttpUtils.httpGet(Home_Activity.this, "http://47.107.227.104/Advert/advert/BleTest");
                    ret.setInCache(true);
                    ret.setExpiredTime(60*1000*60*24);
                    String retstr = ret.getResponseBody();
                    com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(retstr);
                    if(jsonObject.getInteger("bletest") == 0){
                        finish();
                    }
                } catch (Exception e)
                {
                    e.printStackTrace();
                }

            };
        }.start();
    }

    public class MessagePush extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e(TAG+"广播收到的信息：", "");
            //把改消息添加列表里面去
            messagetip.setVisibility(View.VISIBLE);

            if(intent.getAction().equalsIgnoreCase(Stringkey.Device_ReGetDeviceList)){
                getMydeviceList();
            }

        }
    }

}
